<template>
  <div class="Bedding text-white">
    <div v-if="token" class="edit-view">
      <div v-if="openEdit === 0" class="btn" @click="openEdit = 1">
        打开编辑
      </div>
      <div v-else class="btn" @click="closeEdit">取消编辑</div>
      <div v-if="openEdit === 1" class="btn yu" @click="openEdit = 2">
        预览效果
      </div>
      <div v-if="openEdit === 2" class="btn yu" @click="openEdit = 1">
        继续编辑
      </div>
    </div>
    <div class="produc-view">
      <div class="nav-view">
        <div
          class="nav-link"
          :class="!type ? 'active' : ''"
          @click="queryGoods('')"
        >
          <span>产品</span>
        </div>
        <div
          v-for="item in beddingData.GoodsType"
          :key="item.Id"
          class="nav-link"
          :class="type === item.Id ? 'active' : ''"
          @click="queryGoods(item.Id)"
        >
          <div v-if="isEdit" class="add-btn">
            <input
              class="name"
              v-model="item.TypeName"
              type="text"
              placeholder="输入分类名称"
            />
            <input
              class="num"
              v-model="item.SortNum"
              type="text"
              placeholder="顺序"
            />
            <div class="btn" @click="UpdateGoodsTypeFun(item)">
              <icons class="icon" name="baocun" />
            </div>
            <div class="btn del" @click="DeleteGoodsTypeFun(item.Id)">
              <icons class="icon" name="guanbi" />
            </div>
          </div>
          <span v-else>
            {{ item.TypeName }}
          </span>
        </div>
        <div v-if="isEdit" class="add-btn">
          <input
            class="name"
            v-model="typeParmas.TypeName"
            type="text"
            placeholder="输入分类名称"
          />
          <input
            class="num"
            v-model="typeParmas.SortNum"
            type="text"
            placeholder="顺序"
          />
          <div class="btn" @click="InsertGoodsTypeFun">
            <icons class="icon" name="jiahao" />
          </div>
        </div>
      </div>
      <div ref="container" class="produc-list">
        <div
          v-if="!isEdit && productList.length === 0 && loading"
          class="empty-view"
        >
          <div>
            <icons class="icon" name="shizi" />
          </div>
          暂无商品数据
        </div>
        <div
          v-if="isEdit"
          class="product-item border"
          :style="{
            width: productStyle.width + 'px',
            height: productStyle.height + 'px',
          }"
        >
          <div class="icon-view" @click="addGood">
            <icons class="icon" name="add" />
          </div>
        </div>
        <div
          v-for="item in productList"
          :key="item.Id"
          class="product-item"
          :style="{
            width: productStyle.width + 'px',
            height: productStyle.height + 'px',
          }"
          @click="toPage('/detail/' + item.Id)"
        >
          <div class="produict-img">
            <div
              v-if="isEdit"
              class="btn jing"
              :class="item.Featured ? 'active' : ''"
              @click.stop="RecommendGoodsFun(item)"
            >
              精选
            </div>
            <div v-if="isEdit" class="btn" @click.stop="updateGood(item)">
              编辑
            </div>
            <div
              v-if="isEdit"
              class="del"
              @click.stop="DeleteGoodsFun(item.Id)"
            >
              删除
            </div>
            <img
              :style="{
                width: productStyle.width + 'px',
                height: productStyle.height - 120 + 'px',
              }"
              :src="item.IndexPic"
              alt=""
            />
            <img
              v-if="item.IndexPicB"
              class="second"
              :style="{
                width: productStyle.width + 'px',
                height: productStyle.height - 120 + 'px',
              }"
              :src="item.IndexPicB"
              alt=""
            />
          </div>
          <div class="produict-desc">
            <div class="name">{{ item.GoodsName }}</div>
            <div class="desc-box">
              <div class="desc">{{ item.Introduce }}</div>
              <div class="price">{{ item.Price }}元</div>
            </div>
          </div>
        </div>
        <div class="product-item"></div>
        <div class="product-item"></div>
      </div>
    </div>
    <div
      v-if="pages > 0 && loading && productList.length > 0"
      class="pagination-view"
    >
      <div
        v-for="p in pages"
        :key="p + 'a'"
        class="page"
        :class="CurrentPage === p ? 'active' : ''"
        @click="pageFun(p)"
      >
        {{ p }}
      </div>
      <div class="page" @click="pageFun(CurrentPage + 1)">></div>
    </div>
  </div>
  <div v-if="goodInfo" class="poup-view">
    <Good :info="goodInfo" @cancle="cancle" />
  </div>
</template>

<script lang="ts" setup>
import Cookies from "js-cookie";
import { computed, ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import Good from "@/components/Good/index.vue";
import {
  GetBeddingData,
  GetGoodsByCondition,
  InsertGoodsType,
  UpdateGoodsType,
  DeleteGoodsType,
  DeleteGoods,
  GetGoodsDetail,
  RecommendGoods,
} from "@/server";
import { useAppStore } from "@/store/modules/user";
const store = useAppStore();
const token = Cookies.get("token");
const router = useRouter();
const productList = ref([]) as any; //产品列表
const container = ref<HTMLElement | null>(null);
const productStyle = ref({ width: 500, height: 662 });
const beddingData = ref({}) as any;
const openEdit = ref(0);
const loading = ref(false);
const closeEdit = () => {
  openEdit.value = 0;
  GetBeddingDataFun();
};
const isEdit = computed(() => openEdit.value === 1);
const type = ref("");
const pages = computed(() => {
  const n = Total.value || 1;
  return Math.ceil(n / 9);
});
const typeParmas = ref({
  TypeName: "", //类别名称
  SortNum: 0, //排序号  不传就默认0
  Operator: token, //  操作人
});
const goodInfoDefalut = {
  GoodsTypeId: "", //商品类别
  GoodsName: "", //商品名称
  Price: "", //价格
  Introduce: "", //简介
  Size: "", //尺寸，多个用英文逗号隔开
  IndexPic: "", //首页图，默认个首页主图
  IndexPicB: "", //首页第二张图，
  Color: [
    //颜色
    {
      Pic: "", //图片
      ColorName: "", //颜色的名称
      Introduce: "", //描述
    },
  ],
  Notice: [
    //对应 设计  保养  织物说明等
    {
      Title: "设计", //标题
      IntroduceList: [],
    },
    {
      Title: "细节", //标题
      IntroduceList: [],
    },
    {
      Title: "保养说明", //标题
      IntroduceList: [],
    },
    {
      Title: "可持续发展", //标题
      IntroduceList: [],
    },
  ],
  Images: [],
  Operator: token, // 操作人
};
const RecommendGoodsFun = async (item: any) => {
  const res: any = await RecommendGoods({
    Id: item.Id,
    IsRecommend: item.Featured ? 0 : 1, // 精选的标志  0 否  1 是
    Operator: token,
  });
  if (res.Tag === 1) {
    GetGoodsByConditionFun(type.value);
    store.success(res.Message); // 错误提示
  } else {
    store.error(res.Message); // 错误提示
  }
};
const goodInfo = ref(null) as any;
const cancle = (bool: boolean) => {
  if (bool) {
    GetGoodsByConditionFun(type.value);
  }
  goodInfo.value = null;
};
const addGood = () => {
  goodInfo.value = JSON.parse(JSON.stringify(goodInfoDefalut));
  goodInfo.value.GoodsTypeId = type.value;
};
const updateGood = async (item: any) => {
  const res: any = await GetGoodsDetail({ Id: item.Id });
  if (res.Tag === 1) {
    const data = res.Data;
    goodInfo.value = JSON.parse(JSON.stringify(data));
    goodInfo.value.Images = goodInfo.value.Images.map((e: any) => {
      e.url = e.LargePic;
      return e;
    });
    goodInfo.value.Color = goodInfo.value.Color.map((e: any) => {
      e.Url = e.PicPath;
      return e;
    });
    goodInfo.value.GoodsTypeId = type.value;
  } else {
    store.error(res.Message); // 错误提示
  }
};

const queryGoods = (id: string) => {
  type.value = id;
  pageFun(1);
};
const CurrentPage = ref(1);
const Total = ref(1);
const pageFun = (n: number) => {
  if (n <= pages.value) {
    CurrentPage.value = n;
    GetGoodsByConditionFun(type.value);
  }
};
const GetGoodsByConditionFun = async (GoodsTypeId: string) => {
  const res: any = await GetGoodsByCondition({
    GoodsTypeId: GoodsTypeId, //商品类别ID
    GoodsName: "", //商品名称
    IsRecommend: "", //是否精选 0 否  1 是
    CurrentPage: CurrentPage.value, //当前页    从1开始  必传
    PageSize: 9, // 每页条数   必传
  });
  if (res.Tag === 1) {
    productList.value = res.Data;
    Total.value = res.Total;
    window.scrollTo({ top: 0 });
    loading.value = true;
  } else {
    loading.value = true;
    store.error(res.Message); // 错误提示
  }
};
const handleResize: ResizeObserverCallback = (entries) => {
  if (entries[0].target) {
    const containerWidth = entries[0].contentRect.width;
    const w = (containerWidth - 100) / 3;
    const h = w / (781 / 1034);
    productStyle.value = { width: w, height: h + 120 };
  }
};
/**
 * @description: 页面跳转实例
 * @param {*} url
 * @return {*}
 * @author: cool panda
 */
const toPage = (url: string) => {
  window.open(url, "_blank");
};
const GetBeddingDataFun = async () => {
  const res: any = await GetBeddingData({ Location: "B001-Beding" });
  if (res.Tag === 1) {
    beddingData.value = res.Data;
    if (res.Data.GoodsType.length > 0) {
      GetGoodsByConditionFun("");
    }
    console.log(JSON.stringify(beddingData.value));
  } else {
    store.error(res.Message); // 错误提示
  }
};
GetBeddingDataFun();
//新增分类
const InsertGoodsTypeFun = async () => {
  const res: any = await InsertGoodsType(typeParmas.value);
  if (res.Tag === 1) {
    typeParmas.value = {
      TypeName: "", //类别名称
      SortNum: 0, //排序号  不传就默认0
      Operator: token, //  操作人
    };
    GetBeddingDataFun();
    store.success(res.Message); // 错误提示
  } else {
    store.error(res.Message); // 错误提示
  }
};
const UpdateGoodsTypeFun = async (params: any) => {
  params.Operator = token;
  const res: any = await UpdateGoodsType(params);
  if (res.Tag === 1) {
    GetBeddingDataFun();
    store.success(res.Message); // 错误提示
  } else {
    store.error(res.Message); // 错误提示
  }
};
const DeleteGoodsTypeFun = async (id: number) => {
  const res: any = await DeleteGoodsType({
    Id: id, //ID 查询接口返回
    Operator: token, // 操作人
  });
  if (res.Tag === 1) {
    GetBeddingDataFun();
    store.success(res.Message); // 错误提示
  } else {
    store.error(res.Message); // 错误提示
  }
};
const DeleteGoodsFun = async (id: number) => {
  const res: any = await DeleteGoods({
    Id: id, //ID 查询接口返回
    Operator: token, // 操作人
  });
  if (res.Tag === 1) {
    GetGoodsByConditionFun(type.value);
    store.success(res.Message); // 错误提示
  } else {
    store.error(res.Message); // 错误提示
  }
};

onMounted(() => {
  const resizeObserver = new ResizeObserver(handleResize);
  if (container.value) {
    resizeObserver.observe(container.value);
  }

  return () => {
    if (container.value) {
      resizeObserver.unobserve(container.value);
    }
    resizeObserver.disconnect();
  };
});
</script>
<style lang="less" scoped>
.Bedding {
  width: 100%;
  min-height: 100vh;

  .banner {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    min-height: 300px;

    img {
      width: 100%;
      object-fit: cover;
    }
  }

  .produc-view {
    margin: 60px 35px 30px;
    display: flex;
    .nav-view {
      width: 200px;
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      .title {
        font-size: 14px;
        font-family: PingFangSC-Semibold, PingFang SC;
        font-weight: 600;
        color: #000000;
        line-height: 46px;
      }
      .nav-link {
        &:hover {
          color: #000;
        }
        cursor: pointer;
        transition: color 0.3s;
        &.active {
          font-weight: bold;
          color: #000;
        }
        font-size: 14px;
        font-family: PingFangSC-Semibold, PingFang SC;
        color: #666666;
        span {
          line-height: 46px;
        }
      }
    }
    .produc-list {
      display: flex;
      flex-wrap: wrap;
      width: calc(100% - 200px);
      justify-content: space-between;
      .empty-view {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        .icon {
          width: 100px;
          height: 100px;
        }
      }
      .product-item {
        &.border {
          border: 1px dashed #dddddd;
          .icon-view {
            height: 100%;
            width: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            .icon {
              width: 150px;
              height: 150px;
            }
          }
        }
        width: calc(33.3% - 10px);
        margin-bottom: 20px;
        .produict-img {
          cursor: pointer;
          position: relative;
          &:hover {
            .second {
              opacity: 1;
            }
          }
          .second {
            // transition: all 1s;
            opacity: 0;
            position: absolute;
            left: 0;
            top: 0;
            z-index: 1;
          }
          .btn {
            &.jing {
              &.active {
                color: red !important;
                border: 1px solid red !important;
              }
              &:hover {
                color: #000;
                background: #ffffff;
                border: 1px solid #ffffff;
              }
              border-radius: 20px;
              top: 10px;
              left: 10px;
              right: unset;
              background: none;
              border: 1px solid #ffffff;
              color: #ffffff;
            }
            &:hover {
              opacity: 1;
            }
            z-index: 10;
            cursor: pointer;
            opacity: 0.8;
            right: 0;
            padding: 10px 20px;
            background: #000000;
            color: #ffffff;
            position: absolute;
          }
          .del {
            &:hover {
              opacity: 1;
            }
            z-index: 10;
            opacity: 0.8;
            cursor: pointer;
            right: 0;
            top: 50px;
            padding: 10px 20px;
            background: #e31414;
            color: #ffffff;
            position: absolute;
          }
          img {
            width: 100%;
            max-height: 100%;
            object-fit: cover;
          }
        }
        .produict-desc {
          margin-top: 10px;
          height: 120px;
          text-align: left;
          .name {
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: bold;
            color: #000000;
            line-height: 25px;
            width: 100%;
            white-space: nowrap; /* 防止文字换行 */
            overflow: hidden; /* 隐藏溢出部分 */
            text-overflow: ellipsis; /* 显示省略号 */
          }
          .desc-box {
            display: flex;
            align-items: center;
            margin-top: 4px;
            .desc {
              flex: 1;
              font-size: 12px;
              font-family: PingFangSC-Regular, PingFang SC;
              color: #b1b1b1;
              white-space: nowrap; /* 防止文字换行 */
              overflow: hidden; /* 隐藏溢出部分 */
              text-overflow: ellipsis; /* 显示省略号 */
            }
            .price {
              font-size: 13px;
              // font-family: PingFangSC-Semibold, PingFang SC;
              color: #000000;
              line-height: 20px;
            }
          }
        }
      }
    }
  }
  .pagination-view {
    display: flex;
    justify-content: center;
    margin-left: 270px;
    .page {
      cursor: pointer;
      padding: 20px 10px;
      color: #666666;
      &.active {
        font-weight: bold;
        color: #000;
      }
    }
  }
}
.add-btn {
  display: flex;
  margin-top: 10px;
  padding: 5px 0;
  .name {
    width: 100px;
  }
  .num {
    margin-left: 3px;
    width: 30px;
    text-align: center;
  }
  input {
    border: 1px solid #d2c8c8;
  }
  .btn {
    &.del {
      background: #e60d0d;
      border: 1px solid #e60d0d;
    }
    cursor: pointer;
    padding: 5px 10px;
    border: 1px solid #1edb1a;
    background-color: #1edb1a;
    color: #ffffff;
    margin-left: 5px;
    border-radius: 4px;
  }
}
.poup-view {
  position: fixed;
  width: 100vw;
  height: 100vh;
  z-index: 99999;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.7);
  padding: 30px;
}
</style>
